<?php
/**
 * description
 *
 * @copyright        2016 opencart.cn - All Rights Reserved
 * @link             http://www.guangdawangluo.com
 * @author           TL <mengwb@opencart.cn>
 * @created          2016-11-08 14:04:00
 * @modified         2016-11-08 14:04:00
 */

class ModelAccountCustomerGd extends Model
{
    public function addCustomer($data)
    {
        if (isset($data['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($data['customer_group_id'], $this->config->get('config_customer_group_display'))) {
            $customer_group_id = $data['customer_group_id'];
        } else {
            $customer_group_id = $this->config->get('config_customer_group_id');
        }

        $this->load->model('account/customer_group');

        $customer_group_info = $this->model_account_customer_group->getCustomerGroup($customer_group_id);

        if (isset($data['email'])) {
            $this->db->query('INSERT INTO '.DB_PREFIX."customer SET customer_group_id = '".(int) $customer_group_id."', store_id = '".(int) $this->config->get('config_store_id')."', language_id = '".(int) $this->config->get('config_language_id')."', firstname = '".$this->db->escape($data['firstname'])."', email = '".$this->db->escape($data['email'])."', custom_field = '".$this->db->escape(isset($data['custom_field']['account']) ? json_encode($data['custom_field']['account']) : '')."', salt = '".$this->db->escape($salt = token(9))."', password = '".$this->db->escape(sha1($salt.sha1($salt.sha1($data['password']))))."', newsletter = '".(isset($data['newsletter']) ? (int) $data['newsletter'] : 0)."', ip = '".$this->db->escape($this->request->server['REMOTE_ADDR'])."', status = '1', approved = '".(int) !$customer_group_info['approval']."', date_added = NOW()");
        } elseif (isset($data['telephone'])) {
            $this->db->query('INSERT INTO '.DB_PREFIX."customer SET customer_group_id = '".(int) $customer_group_id."', store_id = '".(int) $this->config->get('config_store_id')."', language_id = '".(int) $this->config->get('config_language_id')."', firstname = '".$this->db->escape($data['firstname'])."', telephone = '".$this->db->escape($data['telephone'])."', custom_field = '".$this->db->escape(isset($data['custom_field']['account']) ? json_encode($data['custom_field']['account']) : '')."', salt = '".$this->db->escape($salt = token(9))."', password = '".$this->db->escape(sha1($salt.sha1($salt.sha1($data['password']))))."', newsletter = '".(isset($data['newsletter']) ? (int) $data['newsletter'] : 0)."', ip = '".$this->db->escape($this->request->server['REMOTE_ADDR'])."', status = '1', approved = '".(int) !$customer_group_info['approval']."', date_added = NOW()");
        }

        $customer_id = $this->db->getLastId();

        $this->load->language('mail/customer');

        if (isset($data['email']) && $data['email']) {
            $subject = sprintf($this->language->get('text_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));

            $message = sprintf($this->language->get('text_welcome'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'))."\n\n";

            if (!$customer_group_info['approval']) {
                $message .= $this->language->get('text_login')."\n";
            } else {
                $message .= $this->language->get('text_approval')."\n";
            }

            $message .= $this->url->link('account/login', '', true)."\n\n";
            $message .= $this->language->get('text_services')."\n\n";
            $message .= $this->language->get('text_thanks')."\n";
            $message .= html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8');

            $mail = new Mail();
            $mail->protocol = $this->config->get('config_mail_protocol');
            $mail->parameter = $this->config->get('config_mail_parameter');
            $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
            $mail->smtp_username = $this->config->get('config_mail_smtp_username');
            $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
            $mail->smtp_port = $this->config->get('config_mail_smtp_port');
            $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

            $mail->setTo($data['email']);
            $mail->setFrom($this->config->get('config_email'));
            $mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
            $mail->setSubject($subject);
            $mail->setText($message);
            $mail->send();
        }

        // Send to main admin email if new account email is enabled
        if (in_array('account', (array) $this->config->get('config_mail_alert'))) {
            $message = $this->language->get('text_signup')."\n\n";
            $message .= $this->language->get('text_website').' '.html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8')."\n";
            $message .= $this->language->get('text_firstname').' '.$data['firstname']."\n";
            $message .= $this->language->get('text_customer_group').' '.$customer_group_info['name']."\n";
            $message .= $this->language->get('text_email').' '.$data['email']."\n";
            $message .= $this->language->get('text_telephone').' '.$data['telephone']."\n";

            $mail = new Mail();
            $mail->protocol = $this->config->get('config_mail_protocol');
            $mail->parameter = $this->config->get('config_mail_parameter');
            $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
            $mail->smtp_username = $this->config->get('config_mail_smtp_username');
            $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
            $mail->smtp_port = $this->config->get('config_mail_smtp_port');
            $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

            $mail->setTo($this->config->get('config_email'));
            $mail->setFrom($this->config->get('config_email'));
            $mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
            $mail->setSubject(html_entity_decode($this->language->get('text_new_customer'), ENT_QUOTES, 'UTF-8'));
            $mail->setText($message);
            $mail->send();

            // Send to additional alert emails if new account email is enabled
            $emails = explode(',', $this->config->get('config_alert_email'));

            foreach ($emails as $email) {
                if (utf8_strlen($email) > 0 && filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $mail->setTo($email);
                    $mail->send();
                }
            }
        }

        return $customer_id;
    }

    public function editCustomer($data)
    {
        $customer_id = $this->customer->getId();

        $this->db->query('UPDATE '.DB_PREFIX."customer SET firstname = '".$this->db->escape($data['firstname'])."', email = '".$this->db->escape($data['email'])."', telephone = '".$this->db->escape($data['telephone'])."', custom_field = '".$this->db->escape(isset($data['custom_field']) ? json_encode($data['custom_field']) : '')."' WHERE customer_id = '".(int) $customer_id."'");
    }

    public function editPassword($customer_id, $password)
    {
        $this->db->query('UPDATE '.DB_PREFIX."customer SET salt = '".$this->db->escape($salt = token(9))."', password = '".$this->db->escape(sha1($salt.sha1($salt.sha1($password))))."', code = '' WHERE customer_id = '".$customer_id."'");
    }

    public function editCode($customer_id, $code)
    {
        $this->db->query('UPDATE `'.DB_PREFIX."customer` SET code = '".$this->db->escape($code)."' WHERE customer_id = '".$customer_id."'");
    }

    public function editNewsletter($newsletter)
    {
        $this->db->query('UPDATE '.DB_PREFIX."customer SET newsletter = '".(int) $newsletter."' WHERE customer_id = '".(int) $this->customer->getId()."'");
    }

    public function getCustomer($customer_id)
    {
        $query = $this->db->query('SELECT c.*, ca.uid AS openid, ca.unionid, cp.avatar FROM '.DB_PREFIX."customer c 
                                    LEFT JOIN " . DB_PREFIX . "customer_profile cp ON cp.customer_id = c.customer_id
                                    LEFT JOIN " . DB_PREFIX . "customer_authentication ca ON ca.customer_id = c.customer_id
                                    WHERE c.customer_id = '".(int) $customer_id."'");
        
      

        return $query->row;
    }

    public function getCustomerById($customer_id)
    {
        $query = $this->db->query('SELECT * FROM '.DB_PREFIX."customer WHERE customer_id = '".$customer_id."'");

        return $query->row;
    }

    public function getCustomerByEmail($email)
    {
        $query = $this->db->query('SELECT * FROM '.DB_PREFIX."customer WHERE LOWER(email) = '".$this->db->escape(utf8_strtolower($email))."'");

        return $query->row;
    }

    public function getCustomerByTelephone($telephone)
    {
        $query = $this->db->query('SELECT * FROM '.DB_PREFIX."customer WHERE telephone = '".$telephone."'");

        return $query->row;
    }

    public function getCustomerByCode($code)
    {
        $query = $this->db->query('SELECT customer_id, firstname, email FROM `'.DB_PREFIX."customer` WHERE code = '".$this->db->escape($code)."' AND code != ''");

        return $query->row;
    }

    public function getCustomerByToken($token)
    {
        $query = $this->db->query('SELECT * FROM '.DB_PREFIX."customer WHERE token = '".$this->db->escape($token)."' AND token != ''");

        $this->db->query('UPDATE '.DB_PREFIX."customer SET token = ''");

        return $query->row;
    }

    public function getTotalCustomersByID($customer_id)
    {
        $query = $this->db->query('SELECT COUNT(*) AS total FROM '.DB_PREFIX."customer WHERE customer_id = '".$customer_id."'");

        return $query->row['total'];
    }

    public function getTotalCustomersByEmail($email)
    {
        $query = $this->db->query('SELECT COUNT(*) AS total FROM '.DB_PREFIX."customer WHERE LOWER(email) = '".$this->db->escape(utf8_strtolower($email))."'");

        return $query->row['total'];
    }

    public function getTotalCustomersByTelephone($telephone)
    {
        $query = $this->db->query('SELECT COUNT(*) AS total FROM '.DB_PREFIX."customer WHERE telephone = '".$telephone."'");

        return $query->row['total'];
    }

    public function getRewardTotal($customer_id)
    {
        $query = $this->db->query('SELECT SUM(points) AS total FROM '.DB_PREFIX."customer_reward WHERE customer_id = '".(int) $customer_id."'");

        return $query->row['total'];
    }

    public function getIps($customer_id)
    {
        $query = $this->db->query('SELECT * FROM `'.DB_PREFIX."customer_ip` WHERE customer_id = '".(int) $customer_id."'");

        return $query->rows;
    }

    public function addLoginAttempt($email)
    {
        $query = $this->db->query('SELECT * FROM '.DB_PREFIX."customer_login WHERE email = '".$this->db->escape(utf8_strtolower((string) $email))."' AND ip = '".$this->db->escape($this->request->server['REMOTE_ADDR'])."'");

        if (!$query->num_rows) {
            $this->db->query('INSERT INTO '.DB_PREFIX."customer_login SET email = '".$this->db->escape(utf8_strtolower((string) $email))."', ip = '".$this->db->escape($this->request->server['REMOTE_ADDR'])."', total = 1, date_added = '".$this->db->escape(date('Y-m-d H:i:s'))."', date_modified = '".$this->db->escape(date('Y-m-d H:i:s'))."'");
        } else {
            $this->db->query('UPDATE '.DB_PREFIX."customer_login SET total = (total + 1), date_modified = '".$this->db->escape(date('Y-m-d H:i:s'))."' WHERE customer_login_id = '".(int) $query->row['customer_login_id']."'");
        }
    }

    public function getLoginAttempts($email)
    {
        $query = $this->db->query('SELECT * FROM `'.DB_PREFIX."customer_login` WHERE email = '".$this->db->escape(utf8_strtolower($email))."'");

        return $query->row;
    }

    public function deleteLoginAttempts($email)
    {
        $this->db->query('DELETE FROM `'.DB_PREFIX."customer_login` WHERE email = '".$this->db->escape(utf8_strtolower($email))."'");
    }

    public function getAvatar($customer_id)
    {
        $query = $this->db->query('SELECT avatar FROM '.DB_PREFIX."customer_profile WHERE customer_id = '".$customer_id."'");

        if ($query->num_rows >0) {
            return $query->row['avatar'];
        } else {
            return 'avatar/default.jpg';
        }
    }
}
